package com.tripleying.dogend.dnfipm.util;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HTTPUtil {
    
    public static JsonObject getUpdateInfo(String requestUrl) {
        String res = "";
        JsonObject object = null;
        StringBuilder buffer = new StringBuilder();
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
            if (200 == urlCon.getResponseCode()) {
                InputStream is = urlCon.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String str = null;
                while ((str = br.readLine()) != null) {
                    buffer.append(str);
                }
                br.close();
                isr.close();
                is.close();
                res = buffer.toString();
                object = JsonParser.parseString(res).getAsJsonObject();
            } else {
                throw new Exception("连接失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }
    
    public static boolean downloadNewFile(String requestUrl, File file) throws Exception {
        int byteread = 0;
        URL url = new URL(requestUrl);
        URLConnection conn = url.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
        httpURLConnection.setRequestProperty("Charset", "UTF-8");
        httpURLConnection.connect();
        InputStream is = httpURLConnection.getInputStream();
        if(!file.exists()) file.createNewFile();
        FileOutputStream fs = new FileOutputStream(file);
        byte[] buffer = new byte[1204];
        while ((byteread = is.read(buffer)) != -1) {
            fs.write(buffer, 0, byteread);
        }
        return file.exists();
    }
    
}
